package com.ai.platform.spider.download;

import com.ai.platform.spider.core.SpiderContext;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 功能描述
 * 创建者 yeyingsheng
 * 创建时间 2018年06月27日
 */
public class DownloadFactory {

    private SpiderContext context;
    private DownloadListener listener;
    private DownloadFactory(){}

    private DownloadFactory(SpiderContext context, DownloadListener listener){
        this.context=context;
        this.listener=listener;
    }

    public static DownloadFactory createDownloadFactory(SpiderContext context, DownloadListener listener){
        return new DownloadFactory(context,listener);
    }

    /**
     * 下载器
     * @param request
     * @return
     */
    public Response downloaderHtml(Request request,Class<? extends Downloader> clazz){
        //反射调用
        try {
            Method method=clazz.getMethod("doDownload",request.getClass());
            Constructor<?> csr = clazz.getConstructor(SpiderContext.class,DownloadListener.class) ;
            Object obj=csr.newInstance(context,listener);
            Response response= (Response) method.invoke(obj,request);
            return response;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载器
     * @param request
     * @return
     */
    public Response downloaderHtml(Request request,String className){
        //反射调用
        try {
            Class clazz=Class.forName(className);
            return downloaderHtml(request,clazz);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
